<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Panel extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/panel
	 *	- or -  
	 * 		http://example.com/index.php/panel/index
	 *	- or -
	 * Since this controller is set as the default controller in 
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/panel/<method_name>
	 * @see http://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct()
	{
		parent::__construct();
		$this->load->model('user','',TRUE);
		session_start();
	}

	public function index()
	{
		if($this->session->userdata('logged_in'))
		{
			$session_data = $this->session->userdata('logged_in');
			$data['username'] = $session_data['username'];
			$this->load->view('panel_control', $data);
		}
		else
		{
			//If no session, redirect to login page
			$this->load->view('front_page');
			//redirect('login', 'refresh');
		}
	}

	public function login()
	{
		$this->load->helper(array('form'));
		$this->load->view('login_form');
	}

	public function logout()
	{
		$this->session->unset_userdata('logged_in');
		session_destroy();
		redirect('panel', 'refresh');
	}

 	public function autenticar()
	{
		//This method will have the credentials validation
		$this->load->library('form_validation');

		$this->form_validation->set_rules('username', 'Username', 'trim|required|xss_clean');
		$this->form_validation->set_rules('password', 'Password', 'trim|required|xss_clean|callback_user_authenticate');

		if($this->form_validation->run() == FALSE)
		{
			//login failed
			redirect('login_form', 'refresh');
		}
		else
		{
			//authenticated
			redirect('panel', 'refresh');
		}

	}

	function user_authenticate($password)
	{
		//Field validation succeeded.  Validate against database
		$username = $this->input->post('username');

		//query the database
		$result = $this->user->login($username, $password);

		if($result)
		{
			$sess_array = array();
			foreach($result as $row)
			{
				$sess_array = array(
					'id' => $row->usuario_id,
					'username' => $row->username
					);
				$this->session->set_userdata('logged_in', $sess_array);
			}
			return true;
		}
		else
		{
			$this->form_validation->set_message('check_database', 'Invalid username or password');
			return false;
		}
	}

}

/* End of file panel.php */
/* Location: ./application/controllers/panel.php */